package com.stp.rabbitmq.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * TTL过期
 * 死信队列配置
 */
@Configuration
public class DeadConfig {
    // 死信交换机
    public static final String DEAD_EXCHANGE_NAME = "dead_exchange";

    // 死信队列
    public static final String DEAD_QUEUE_NAME = "dead_queue";

    // 自定义延时交换机
    public static final String CUSTOM_DELAY_EXCHANGE_NAME = "custom_delay_exchange";

    // 延时交换机
    @Bean
    public Exchange customDelayExchange() {
        Map<String, Object> arguments = new HashMap<>(1);
        arguments.put("x-delayed-type", "direct");
        return new CustomExchange(CUSTOM_DELAY_EXCHANGE_NAME, "x-delayed-message", true, false, arguments);
    }

    // 死信交换机
    @Bean
    public Exchange deadExchange() {
        return new DirectExchange(DEAD_EXCHANGE_NAME);
    }

    /**
     * 死信队列
     * maxLength() 指定队列的最大长度
     * withArgument("x-max-priority",10) 优先级队列
     * @return
     */
    @Bean
    public Queue deadQueue() {
        return QueueBuilder.durable(DEAD_QUEUE_NAME)
                .withArgument("x-max-priority",10)
                .build();
    }

    // 绑定死信交换机和死信队列
    @Bean
    public Binding deadBinding11(@Qualifier("deadQueue") Queue deadQueue
            , @Qualifier("deadExchange") Exchange deadExchange) {
        return BindingBuilder.bind(deadQueue)
                .to(deadExchange)
                .with(DEAD_QUEUE_NAME)
                .noargs();
    }

    @Bean
    public Binding deadBindingDelay(@Qualifier("deadQueue") Queue deadQueue
            , @Qualifier("customDelayExchange") Exchange customDelayExchange) {
        return BindingBuilder.bind(deadQueue)
                .to(customDelayExchange)
                .with(DEAD_QUEUE_NAME)
                .noargs();
    }
}
